package com.eastcom.mystope.daemon.provider;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.eastcom.mystope.daemon.context.ServerContext;


/**
 * @author yuanyue
 * @describe 实现动态数据源切换逻辑
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
	private Log log = LogFactory.getLog(DynamicDataSource.class);
	private Map<Object, Object> targetDataSources = new HashMap<Object, Object>();

	
	/**
	 * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey()
	 * @describe 数据源为空或者为0时，自动切换至默认数据源，即在配置文件中定义的dataSource数据源
	 */
	@Override
	protected Object determineCurrentLookupKey() {
		String dataSourceName = ServerContext.getCustomerType();
        return dataSourceName;
	}
	

	@Override
	public void setTargetDataSources(Map<Object, Object> targetDataSources) {
		this.targetDataSources = targetDataSources;
		super.setTargetDataSources(this.targetDataSources);
		afterPropertiesSet();
	}

	public void addTargetDataSource(String key, BasicDataSource dataSource) {
		this.targetDataSources.put(key, dataSource);
		this.setTargetDataSources(this.targetDataSources);
	}

	public BasicDataSource createDataSource(String driverClassName, String url,
			String username, String password) {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setTestWhileIdle(true);
		return dataSource;
	}

	/**
	 * @param serverName
	 * @param dataSource
	 */
	public void setDataSource(String serverName, BasicDataSource dataSource) {
		this.addTargetDataSource(serverName, dataSource);
	}


	@Override
	public void afterPropertiesSet() {
		// TODO 自动生成的方法存根
		super.setTargetDataSources(targetDataSources);
		super.afterPropertiesSet();
	}
	
	
}
